﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomPlacement : MonoBehaviour {
    public Transform target;

    Transform _thisTransform;
    List<Vector3> _verts = new List<Vector3>();
    List<Vector3> _normals = new List<Vector3>();
    Material _targetMat;
    Color[] _colors;
    int _count = -1;

    void Start() {
        _thisTransform = transform;
        var verts = GetComponent<MeshFilter>().mesh.vertices;
        var normals = GetComponent<MeshFilter>().mesh.normals;

        for (var i = 0; i < normals.Length; i++) {
            if (normals[i].z <= 0f) {
                continue;
            }

            _verts.Add(verts[i]);
            _normals.Add(normals[i]);
        }

        _targetMat = new Material(target.GetChild(0).GetComponent<Renderer>().material);
        _colors = new Color[] {
            CakeShopColor.Blueberry, 
            CakeShopColor.Orange, 
            CakeShopColor.Apple, 
            CakeShopColor.Rose, 
            CakeShopColor.Strawberry, 
            CakeShopColor.Pineapple
        };

        _count = _verts.Count;
    }

    bool kk = true;
   
    void Update() {
        if (kk == false || _verts.Count <= 0)
            return;

        StartCoroutine(TimeUtility.DelayInvoke(0.1f, () => RandomGenerate()));
        kk = false;
    }
	
	public void RandomGenerate() {
        kk = true;
        var index = Random.Range(0, _verts.Count);
        var color = _colors[Random.Range(0, _colors.Length)];
        var rotation = Quaternion.identity;
        var t = Instantiate(target, _thisTransform.TransformPoint(_verts[index]), Quaternion.identity, _thisTransform.parent);
        var child = t.GetChild(0);
        child.localEulerAngles = Vector3.up * Random.Range(0f, 360f);
        var mat = new Material(_targetMat);
        mat.color = color;
        child.GetComponent<Renderer>().material = mat;
        _count--;
        _verts.RemoveAt(index);
    }
}
